package com.pig4cloud.pig.goods.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MiaoshaController {

	@Resource(name = "redisCacheTemplate")
	private RedisTemplate redisTemplate;

	@RequestMapping("init")
	public void init(){
		HashMap<String, Object> map = new HashMap<>();
		map.put("goods1",5);
		redisTemplate.opsForHash().putAll("ms_goods",map);
	}
	@RequestMapping("clear")
	public void clear(){
		Set<String> keys = redisTemplate.keys("*");
		redisTemplate.delete(keys);
	}

	@RequestMapping("ms")
	public Object ms(){
		redisTemplate.watch("ms_goods");
		redisTemplate.setEnableTransactionSupport(true);

		Map msGoods = redisTemplate.opsForHash().entries("ms_goods");
		Integer num = (Integer) msGoods.get("goods1");

		redisTemplate.multi();

		if(num>0){
			redisTemplate.opsForHash().increment("ms_goods", "goods1", -1);

		}
		redisTemplate.exec();


		return num;
	}
}
